<?php
namespace app\fowl\controller;

import('aliyun-sdk.aliyun-php-sdk-core.Config', EXTEND_PATH,'.php');
use cmf\controller\AdminBaseController;
use think\Validate;
use Cdn\Request\V20141111 as cdn;
use live\Request\V20161101 as live;

class AlsdkController extends AdminBaseController
{

	private $accessKeyId = 'LTAI43IaLlg1OyT3';

	private $accessSecret = 'VhxyM1yJs2j2vE5zORaXGeZFkioYBs';

	private $client;

	public function  __construct()
	{
		parent::__construct();
		error_reporting(E_ERROR | E_PARSE); // 定义错误级别
		$iClientProfile = \DefaultProfile::getProfile("cn-hangzhou", $this->accessKeyId, $this->accessSecret);
		$this->client = new \DefaultAcsClient($iClientProfile);
	}

	/**
	 * 发送请求
	 * @param  [obj] $[request] [<SDK对象>]
	 */
	public function alsdkRequest($request)
	{
		# 发起请求并处理返回
		try {
		    return $this->client->getAcsResponse($request);
		} catch(ServerException $e) {
		    return ["Error" => $e->getErrorCode(), "Message" => $e->getMessage()];
		} catch(ClientException $e) {
		    return ["Error" => $e->getErrorCode(), "Message" => $e->getMessage()];
		}
	}

	/**
	 * 鉴权函数
	 * @param  [string] $[url] [<推流、播流域名>]
	 * @param  [int] $[time] [<过期时间>]
	 * @param [string] $[key] [<主键>]
	 * @param [string] $[filename] [<模板名>]
	 */
	function PrivateKeyA($url, $time=0, $key='', $filename=''){
      $time=strtotime("+8 hours");
      $key=$key;
      $domain=$url;
      $filename=$filename;
      //$sstring = "URI-Timestamp-rand-uid-PrivateKey"
      $sstring = $filename."-".$time."-0-0-".$key;
      $md5=md5($sstring);
      $auth_key="auth_key=".$time."-0-0-".$md5;
      $url=$domain.$filename."?".$auth_key;
      return $url;
	}

	/**
	 * [testaddress 生成测试账号]
	 * @return [type] [description]
	 */
	public function testaddress()
	{
		echo '推流地址：rtmp://'.$this->PrivateKeyA('tl.puxiansheng.net', '', 'wfPgKwySdz', '/ceshi/5');
		echo "<br>";
		echo '播流地址：rtmp://'.$this->PrivateKeyA('live.puxiansheng.net', '', 'pCvwNPvwmn', '/ceshi/5');
		echo "<br>";
		echo '播流地址：http://'.$this->PrivateKeyA('live.puxiansheng.net', '', 'pCvwNPvwmn', '/ceshi/5.flv');
		echo "<br>";
		echo '播流地址：http://'.$this->PrivateKeyA('live.puxiansheng.net', '', 'pCvwNPvwmn', '/ceshi/5.m3u8');
	}


	/********************************************************/

	/**
	 * [DescribeUserDomains 域名管理]
	 */
	public function DescribeUserDomains()
	{
        // 查询条件
        $param = $this->request->param();
		$request = new cdn\DescribeUserDomainsRequest();
		$search = array();
        if ( request()->isPost() ) {
            if ( isset($param['keyword']) && !empty($param['keyword']) ) {
            	$request->setDomainName($param['keyword']);
            }
            isset($param['keyword']) ? $search['keyword'] = $param['keyword'] : '';
        }
		$data = $this->alsdkRequest($request);

		$this->assign([
            'count'     => $data->TotalCount,
            'list'		=> $data->Domains->PageData,
            'search'	=> $search,
        ]);
        return $this->fetch();
	}

	/**
	 * [DeleteLiveDomain 删除域名]
	 */
	public function DeleteLiveDomain()
	{
		$param = request()->param();
		// 数据验证
		$rule = [
			'domain' => 'require',
        ];
        $validate = new Validate($rule);
        if(!$validate->check($param)){
        	$this->error($validate->getError());exit;
        }

        $request = new live\DeleteLiveDomainRequest();
		$request->setDomainName($param['domain']);
		try {
		    $this->client->getAcsResponse($request);
		    $this->success('删除成功', 'Alsdk/DescribeUserDomains');exit;
		} catch(ServerException $e) {
		    $this->error('删除失败，失败原因：'.$e->getMessage());exit;
		} catch(ClientException $e) {
			$this->error('删除失败，失败原因：'.$e->getMessage());exit;
		}
	}

	/**
	 * [AddLiveDomain 添加域名]
	 */
	public function AddLiveDomain()
	{
		$param = request()->param();
		if ( request()->isPost() ) {
			// 数据验证
			$rule = [
				'DomainName' => 'require',
                'LiveDomainType' 	=> 'require',
                'Region'	=> 'require',
                'Scope'	=> 'require'
            ];
            $validate = new Validate($rule);
            if(!$validate->check($param)){
            	$this->error($validate->getError());exit;
            }

            $request = new live\AddLiveDomainRequest();
			$request->setDomainName($param['DomainName']);
			$request->setLiveDomainType($param['LiveDomainType']);
			$request->setRegion($param['Region']);
			$request->setScope($param['Scope']);

			try {
			    $this->client->getAcsResponse($request);
			    $this->success('添加成功', 'Alsdk/DescribeUserDomains');exit;
			} catch(ServerException $e) {
			    $this->error('添加失败，失败原因：'.$e->getMessage());exit;
			} catch(ClientException $e) {
				$this->error('添加失败，失败原因：'.$e->getMessage());exit;
			}
		} else {
			return $this->fetch();
		}
	}

	/**
	 * [AddLiveDomainMapping 域名映射]
	 */
	public function AddLiveDomainMapping()
	{
		$param = request()->param(); // 获取用户传参
		if ( request()->isPost() ) {
			// 数据验证
			$rule = [
				'PushDomain' => 'require',
                'PullDomain' 	=> 'require',
            ];
            $validate = new Validate($rule);
            if(!$validate->check($param)){
            	$this->error($validate->getError());exit;
            }

            $request = new cdn\AddLiveDomainMappingRequest();
			$request->setPushDomain($param['PushDomain']);
			$request->setPullDomain($param['PullDomain']);
			// print_r($request);
			// exit;

			try {
			    $this->client->getAcsResponse($request);
			    $this->success('映射成功', 'Alsdk/DescribeUserDomains');exit;
			} catch(ServerException $e) {
			    $this->error('映射失败，失败原因：'.$e->getMessage());exit;
			} catch(ClientException $e) {
				$this->error('映射失败，失败原因：'.$e->getMessage());exit;
			}
		} else {
			if ( !isset($param['domain']) || empty($param['domain']) ) {
				$this->error('缺少参数');exit;
			}
			$request = new cdn\DescribeUserDomainsRequest();
			$request->setCdnType('liveVideo');
			$data = $this->alsdkRequest($request);
			$this->assign([
	            'list'		=> $data->Domains->PageData,
	            'domain'	=> $param['domain'],
	        ]);

			return $this->fetch();
		}
	}

	/**
	 * [DescribeLiveDomainDetail 查看域名基本信息]
	 */
	public function DescribeLiveDomainDetail()
	{
		$param = request()->param(); // 获取用户传参
		if ( !isset($param['domain']) || empty($param['domain']) ) {
			$this->error('缺少参数');exit;
		}
		$request = new live\DescribeLiveDomainDetailRequest();
		$request->setDomainName($param['domain']);
		$info = $this->alsdkRequest($request);

		$this->assign([
            'info'     => $info->DomainDetail,
        ]);
        return $this->fetch();
	}

	/**
	 * [StatusLiveDomain 修改域名状态]
	 */
	public function StatusLiveDomain()
	{
		$param = request()->param(); // 获取用户传参
		if ( !isset($param['domain']) || empty($param['domain']) || !isset($param['status']) || empty($param['status']) ) {
			$this->error('缺少参数');exit;
		}

		if ( $param['status'] == 'online' ) {
			$request = new live\StopLiveDomainRequest(); // 停止域名
		} elseif ( $param['status'] == 'offline' ) {
			$request = new live\StartLiveDomainRequest(); // 启动域名
		} else {
			$this->error('参数不合法');exit;
		}
		$request->setDomainName($param['domain']);
		try {
		    $this->client->getAcsResponse($request);
		    $this->success('操作成功');exit;
		} catch(ServerException $e) {
		    $this->error('操作失败，失败原因：'.$e->getMessage());exit;
		} catch(ClientException $e) {
			$this->error('操作失败，失败原因：'.$e->getMessage());exit;
		}
	}

	/********************************************************/

	/**
	 * [DescribeLiveStreamTranscodeInfo 查询转码配置信息]
	 */
	public function DescribeLiveStreamTranscodeInfo()
	{
		$param = request()->param(); // 获取用户传参
		if ( !isset($param['domain']) || empty($param['domain']) ) {
			$this->error('缺少参数');exit;
		}

		$request = new live\DescribeLiveStreamTranscodeInfoRequest();
		$request->setDomainTranscodeName($param['domain']);
		$info = $this->alsdkRequest($request);

		$this->assign([
            'info'     	=> $info->DomainTranscodeList->DomainTranscodeInfo,
            'domain'	=> $param['domain'],
        ]);
        return $this->fetch();
	}

	/**
	 * [AddLiveStreamTranscode 添加转码配置]
	 */
	public function AddLiveStreamTranscode()
	{
		$param = request()->param(); // 获取用户传参
		if ( request()->isPost() ) {
			// 数据验证
			$rule = [
				'App' => 'require',
                'Template' 	=> 'require',
            ];
            $validate = new Validate($rule);
            if(!$validate->check($param)){
            	$this->error($validate->getError());exit;
            }

            $request = new live\AddLiveStreamTranscodeRequest();
			$request->setApp($param['App']);
			$request->setDomain($param['Domain']);
			$request->setTemplate($param['Template']);
			
			try {
			    $this->client->getAcsResponse($request);
			    $this->success('添加成功', 'Alsdk/DescribeLiveStreamTranscodeInfo?domain='.$param['Domain']);exit;
			} catch(ServerException $e) {
			    $this->error('添加失败，失败原因：'.$e->getMessage());exit;
			} catch(ClientException $e) {
				$this->error('添加失败，失败原因：'.$e->getMessage());exit;
			}
		} else {
			if ( !isset($param['domain']) || empty($param['domain']) ) {
				$this->error('缺少参数');exit;
			}

			$this->assign([
	            'domain'	=> $param['domain'],
	        ]);
			return $this->fetch();
		}
	}

	/**
	 * [AddCustomLiveStreamTranscode 添加自定义转码配置]
	 */
	public function AddCustomLiveStreamTranscode()
	{
		$param = request()->param(); // 获取用户传参
		if ( request()->isPost() ) {
			// 数据验证
			$rule = [
				'App' => 'require',
                'Domain' 	=> 'require',
                'FPS' 	=> 'require|number',
                'Width' 	=> 'require|number',
                'Height' 	=> 'require|number',
                'Template' 	=> 'require',
                'VideoBitrate' 	=> 'require|number',
                'TemplateType' 	=> 'require',
            ];
            $msg = [
			    'App.require' => 'AppName不能为空',
			    'Domain.require'     => '参数有误',
			    'FPS.require'   => '转码视频帧率不能为空',
			    'FPS.number'  => '转码视频帧率只能是数字',
			    'Width.require'        => '视频宽度不能为空',
			    'Width.number'        => '视频宽度只能是数字',
			    'Height.require'        => '视频高度不能为空',
			    'Height.number'        => '视频高度不能为空',
			    'Template.require'        => '模板自定义名称不能为空',
			    'VideoBitrate.require'        => '转码视频比特率不能为空',
			    'VideoBitrate.number'        => '转码视频比特率只能是数字',
			];

            $validate = new Validate($rule, $msg);
            if(!$validate->check($param)){
            	$this->error($validate->getError());exit;
            }

            $request = new live\AddCustomLiveStreamTranscodeRequest();
			$request->setApp($param['App']);
			$request->setDomain($param['Domain']);
			$request->setFPS($param['FPS']);
			$request->setWidth($param['Width']);
			$request->setHeight($param['Height']);
			$request->setTemplate($param['Template']);
			$request->setVideoBitrate($param['VideoBitrate']);
			$request->setTemplateType($param['TemplateType']);
			
			try {
			    $this->client->getAcsResponse($request);
			    $this->success('添加成功', 'Alsdk/DescribeLiveStreamTranscodeInfo?domain='.$param['Domain']);exit;
			} catch(ServerException $e) {
			    $this->error('添加失败，失败原因：'.$e->getMessage());exit;
			} catch(ClientException $e) {
				$this->error('添加失败，失败原因：'.$e->getMessage());exit;
			}
		} else {
			if ( !isset($param['domain']) || empty($param['domain']) ) {
				$this->error('缺少参数');exit;
			}

			$this->assign([
	            'domain'	=> $param['domain'],
	        ]);
			return $this->fetch();
		}
	}

	/**
	 * [DeleteLiveStreamTranscode 删除转码配置]
	 */
	public function DeleteLiveStreamTranscode()
	{
		$param = request()->param();
		// 数据验证
		$rule = [
			'App' => 'require',
			'Domain' => 'require',
			'Template' => 'require',
        ];
        $validate = new Validate($rule);
        if(!$validate->check($param)){
        	$this->error($validate->getError());exit;
        }

        $request = new live\DeleteLiveStreamTranscodeRequest();
		$request->setApp($param['App']);
		$request->setDomain($param['Domain']);
		$request->setTemplate($param['Template']);
		try {
		    $this->client->getAcsResponse($request);
		    $this->success('删除成功');exit;
		} catch(ServerException $e) {
		    $this->error('删除失败，失败原因：'.$e->getMessage());exit;
		} catch(ClientException $e) {
			$this->error('删除失败，失败原因：'.$e->getMessage());exit;
		}
	}

	/********************************************************/

	/**
	 * [DescribeLiveRecordConfig 查询域名下录制配置列表]
	 */
	public function DescribeLiveRecordConfig()
	{
		!$param = request()->param(); // 获取用户传参
		if ( !isset($param['domain']) || empty($param['domain']) ) {
			$this->error('缺少参数');exit;
		}
		$search = array();

		$request = new live\DescribeLiveRecordConfigRequest();
		if ( request()->isPost() ) {
            if ( isset($param['keyword']) && !empty($param['keyword']) ) $request->setAppName($param['keyword']);
            if ( isset($param['Order']) && !empty($param['Order']) ) $request->setOrder($param['Order']);
            isset($param['keyword']) ? $search['keyword'] = $param['keyword'] : '';
            isset($param['Order']) ? $search['Order'] = $param['Order'] : '';
        }
		$request->setDomainName($param['domain']);
		$info = $this->alsdkRequest($request);

		// 查询回调地址
		$Notify = new live\DescribeLiveRecordNotifyConfigRequest();
		$Notify->setDomainName($param['domain']);
		$NotifyInfo = $this->alsdkRequest($Notify);

		$this->assign([
            'info'     	=> $info->LiveAppRecordList->LiveAppRecord,
            'domain'	=> $param['domain'],
            'count'		=> $info->PageNum,
            'order'		=> $info->Order,
            'search'	=> $search,
            'Notify'	=> $NotifyInfo->LiveRecordNotifyConfig->NotifyUrl,
        ]);
        return $this->fetch();
	}

	/**
	 * [AddLiveAppRecordConfig 添加APP录制配置]
	 */
	public function AddLiveAppRecordConfig()
	{
		$param = request()->param(); // 获取用户传参
		if ( request()->isPost() ) {
			// 数据验证
			$rule = [
				'AppName' => 'require',
            ];
            $validate = new Validate($rule);
            if(!$validate->check($param)){
            	$this->error($validate->getError());exit;
            }

            $data[0] = [
				'SliceOssObjectPrefix'=>$param['SliceOssObjectPrefix'] ? $param['SliceOssObjectPrefix'] : '',
				'Format'=>$param['Format'],
				'OssObjectPrefix'=>$param['OssObjectPrefix'],
				'CycleDuration'=>$param['CycleDuration'] ? $param['CycleDuration'] : '3600',
			];
			$request = new live\AddLiveAppRecordConfigRequest();
			$request->setAppName($param['AppName']);
			$request->setStreamName($param['StreamName']?$param['StreamName']:'*');
			$request->setDomainName($param['Domain']);
			$request->setOssBucket($param['OssBucket']);
			$request->setOssEndpoint($param['OssEndpoint']);
			$request->setRecordFormats($data);
			
			try {
			    $this->client->getAcsResponse($request);
			    $this->success('添加成功', 'Alsdk/DescribeLiveRecordConfig?domain='.$param['Domain']);exit;
			} catch(ServerException $e) {
			    $this->error('添加失败，失败原因：'.$e->getMessage());exit;
			} catch(ClientException $e) {
				$this->error('添加失败，失败原因：'.$e->getMessage());exit;
			}
		} else {
			if ( !isset($param['domain']) || empty($param['domain']) ) {
				$this->error('缺少参数');exit;
			}

			$this->assign([
	            'domain'	=> $param['domain'],
	        ]);
			return $this->fetch();
		}
	}

	/**
	 * [DeleteLiveAppRecordConfig 删除APP录制配置]
	 */
	public function DeleteLiveAppRecordConfig()
	{
		$param = request()->param();
		// 数据验证
		$rule = [
			'AppName' => 'require',
			'DomainName' => 'require',
			'StreamName' => 'require',
        ];
        $validate = new Validate($rule);
        if(!$validate->check($param)){
        	$this->error($validate->getError());exit;
        }

        $request = new live\DeleteLiveAppRecordConfigRequest();
		$request->setAppName($param['AppName']);
		$request->setDomainName($param['DomainName']);
		$request->setStreamName($param['StreamName']);
		try {
		    $this->client->getAcsResponse($request);
		    $this->success('删除成功');exit;
		} catch(ServerException $e) {
		    $this->error('删除失败，失败原因：'.$e->getMessage());exit;
		} catch(ClientException $e) {
			$this->error('删除失败，失败原因：'.$e->getMessage());exit;
		}
	}

	/**
	 * [AddLiveRecordNotifyConfig 添加录制回调配置]
	 */
	public function AddLiveRecordNotifyConfig()
	{
		$param = request()->param(); // 获取用户传参
		if ( request()->isPost() ) {
			// 数据验证
			$rule = [
				'NotifyUrl' => 'require|url',
            ];
            $msg = [
			    'NotifyUrl.require' => '回调地址不能为空',
			    'NotifyUrl.url'     => '回调地址不合法',
			];
            $validate = new Validate($rule, $msg);
            if(!$validate->check($param)){
            	$this->error($validate->getError());exit;
            }

			$request = new live\AddLiveRecordNotifyConfigRequest();
			$request->setDomainName($param['Domain']);
			$request->setNotifyUrl($param['NotifyUrl']);
			
			try {
			    $this->client->getAcsResponse($request);
			    $this->success('添加成功', 'Alsdk/DescribeLiveRecordConfig?domain='.$param['Domain']);exit;
			} catch(ServerException $e) {
			    $this->error('添加失败，失败原因：'.$e->getMessage());exit;
			} catch(ClientException $e) {
				$this->error('添加失败，失败原因：'.$e->getMessage());exit;
			}
		} else {
			if ( !isset($param['domain']) || empty($param['domain']) ) {
				$this->error('缺少参数');exit;
			}

			$this->assign([
	            'domain'	=> $param['domain'],
	        ]);
			return $this->fetch();
		}
	}

	/**
	 * [DeleteLiveRecordNotifyConfig 删除录制回调配置]
	 */
	public function DeleteLiveRecordNotifyConfig()
	{
		$param = request()->param();
		// 数据验证
		$rule = [
			'DomainName' => 'require',
        ];
        $validate = new Validate($rule);
        if(!$validate->check($param)){
        	$this->error($validate->getError());exit;
        }

        $request = new live\DeleteLiveRecordNotifyConfigRequest();
		$request->setDomainName($param['DomainName']);
		try {
		    $this->client->getAcsResponse($request);
		    $this->success('删除成功');exit;
		} catch(ServerException $e) {
		    $this->error('删除失败，失败原因：'.$e->getMessage());exit;
		} catch(ClientException $e) {
			$this->error('删除失败，失败原因：'.$e->getMessage());exit;
		}
	}
}